package com.lzp.wechat.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import com.lzp.wechat.common.constants.RedisConstants;
import com.lzp.wechat.common.utils.RedisCacheUtils;
import com.lzp.wechat.entity.WeiXinParameter;
import com.lzp.wechat.service.MediaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


@Slf4j
@Service
public class MediaServiceImpl implements MediaService {

    @Autowired
    private WeiXinParameter weiXinParameter;

    @Autowired
    private RedisCacheUtils redisCacheUtils;

    @Override
    public String mediaUpload(MultipartFile multipartFile) {
        String result = "";
        String access_token = redisCacheUtils.get(RedisConstants.ACCESS_TOKEN).toString();
        String url = weiXinParameter.getMediaUploadUrl();
        url = url.replace("ACCESS_TOKEN", access_token).replace("TYPE", "image");
        HttpPost httpPost = new HttpPost(url);
        File file = this.multipartFileToFile(multipartFile);
        FileBody fileBody = new FileBody(file);
        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("media", fileBody)
                .build();
        httpPost.setEntity(reqEntity);

        try {
            CloseableHttpResponse httpResponse = HttpClients.createDefault().execute(httpPost);
            InputStream inputStream = httpResponse.getEntity().getContent();
            result = IoUtil.read(inputStream, "utf-8");
            log.info("调用腾讯新增临时素材响应：{}", result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("新增临时素材异常：{}", e.getMessage());
        }
        return result;
    }

    /**
     * MultipartFile类型转换为File类型
     *
     * @param multipartFile
     * @return
     */
    public static File multipartFileToFile(MultipartFile multipartFile) {
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        try {
            File file = File.createTempFile(System.currentTimeMillis() + "", suffix);
            multipartFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("MultipartFile类型转换为File类型异常：{}", e.getMessage());
        }
        return null;
    }

    @Override
    public void getMediaById(String media_id, HttpServletResponse response) {
        String access_token = redisCacheUtils.get(RedisConstants.ACCESS_TOKEN).toString();
        String url = weiXinParameter.getMediaGetUrl();
        url = url.replace("ACCESS_TOKEN", access_token).replace("MEDIA_ID", media_id);
        byte[] bytes = HttpUtil.downloadBytes(url);
        try {
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
